package com.nutrition.health.controller;

import com.nutrition.health.model.UserHealthProfile;
import com.nutrition.health.model.UserHealthProfileDTO;
import com.nutrition.health.service.DeepSeekAIService;
import com.nutrition.health.service.UserHealthProfileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map;

@RestController
@RequestMapping("/users/{userId}/health-profile")
@Api(tags = "用户健康档案", description = "用户健康档案和个性化健康建议相关操作")
@CrossOrigin(origins = "*")
public class UserHealthProfileController {

    private final UserHealthProfileService profileService;
    private final DeepSeekAIService deepSeekAIService;

    @Autowired
    public UserHealthProfileController(UserHealthProfileService profileService, DeepSeekAIService deepSeekAIService) {
        this.profileService = profileService;
        this.deepSeekAIService = deepSeekAIService;
    }

    @GetMapping
    @ApiOperation("获取用户健康档案")
    public ResponseEntity<UserHealthProfileDTO> getUserHealthProfile(@PathVariable Long userId) {
        return profileService.getProfileWithUserInfo(userId)
                .map(profileDTO -> new ResponseEntity<>(profileDTO, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    
    @GetMapping("/basic")
    @ApiOperation("获取用户基本健康档案（不包含用户信息）")
    public ResponseEntity<UserHealthProfile> getUserBasicHealthProfile(@PathVariable Long userId) {
        return profileService.getProfileByUserId(userId)
                .map(profile -> new ResponseEntity<>(profile, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PostMapping
    @ApiOperation("创建用户健康档案")
    public ResponseEntity<UserHealthProfile> createUserHealthProfile(
            @PathVariable Long userId,
            @Valid @RequestBody UserHealthProfile profile) {

        try {
            System.out.println("接收到创建健康档案请求，userId: " + userId);
            System.out.println("健康档案数据: " + profile);

            UserHealthProfile createdProfile = profileService.createProfile(userId, profile);
            System.out.println("健康档案创建成功，ID: " + createdProfile.getId());

            return new ResponseEntity<>(createdProfile, HttpStatus.CREATED);
        } catch (Exception e) {
            System.err.println("创建健康档案时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @PutMapping
    @ApiOperation("更新用户健康档案")
    public ResponseEntity<UserHealthProfile> updateUserHealthProfile(
            @PathVariable Long userId,
            @Valid @RequestBody UserHealthProfile profileDetails) {

        UserHealthProfile updatedProfile = profileService.updateProfile(userId, profileDetails);
        return new ResponseEntity<>(updatedProfile, HttpStatus.OK);
    }

    @DeleteMapping
    @ApiOperation("删除用户健康档案")
    public ResponseEntity<Void> deleteUserHealthProfile(@PathVariable Long userId) {
        profileService.deleteProfile(userId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/bmr")
    @ApiOperation("计算用户的基础代谢率")
    public ResponseEntity<Map<String, Double>> calculateBMR(@PathVariable Long userId) {
        double bmr = profileService.calculateBMR(userId);
        Map<String, Double> bmrMap = new HashMap<>();
        bmrMap.put("bmr", bmr);
        return new ResponseEntity<>(bmrMap, HttpStatus.OK);
    }

    @GetMapping("/daily-calorie-needs")
    @ApiOperation("计算用户的每日卡路里需求")
    public ResponseEntity<Map<String, Double>> calculateDailyCalorieNeeds(@PathVariable Long userId) {
        double calorieNeeds = profileService.calculateDailyCalorieNeeds(userId);
        Map<String, Double> calorieNeedsMap = new HashMap<>();
        calorieNeedsMap.put("calorieNeeds", calorieNeeds);
        return new ResponseEntity<>(calorieNeedsMap, HttpStatus.OK);
    }

    @GetMapping("/bmi")
    @ApiOperation("计算用户的BMI指数")
    public ResponseEntity<Map<String, Object>> calculateBMI(@PathVariable Long userId) {
        double bmi = profileService.calculateBMI(userId);
        String category = profileService.getBMICategory(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("bmi", bmi);
        map.put("category", category);
        return new ResponseEntity<>(
                map,
                HttpStatus.OK);
    }

    @GetMapping("/nutrient-requirements")
    @ApiOperation("获取用户的营养素需求")
    public ResponseEntity<Map<String, Double>> getNutrientRequirements(@PathVariable Long userId) {
        Map<String, Double> requirements = profileService.generateNutrientRequirements(userId);
        return new ResponseEntity<>(requirements, HttpStatus.OK);
    }

    @GetMapping("/health-recommendations")
    @ApiOperation("获取个性化健康建议")
    public ResponseEntity<Map<String, String>> getHealthRecommendations(@PathVariable Long userId) {
        Map<String, String> recommendations = profileService.generateHealthRecommendations(userId);
        return new ResponseEntity<>(recommendations, HttpStatus.OK);
    }

    @GetMapping("/diet-plan")
    @ApiOperation("获取个性化饮食计划")
    public ResponseEntity<Map<String, Object>> getDietPlan(@PathVariable Long userId) {
        Map<String, Object> dietPlan = profileService.generateDietPlan(userId);
        return new ResponseEntity<>(dietPlan, HttpStatus.OK);
    }

    @GetMapping("/test-endpoint")
    @ApiOperation("测试端点")
    public ResponseEntity<Map<String, Object>> test(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", "测试成功");
        response.put("userId", userId);
        response.put("timestamp", new Date().toString());
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    
    @GetMapping(value = "/ai-health-advice", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ApiOperation("获取AI生成的个性化健康建议（流式返回）")
    public SseEmitter getAIHealthAdvice(
            @PathVariable Long userId,
            @RequestParam(required = false) String overridePrompt,
            @RequestParam(required = false) Map<String, Object> foodData) {
        
        // 创建SSE发射器，设置超时时间为5分钟
        SseEmitter emitter = new SseEmitter(300000L);
        
        // 获取用户健康档案
        try {
            // 使用Java 8兼容的方式处理Optional
            java.util.Optional<UserHealthProfile> profileOpt = profileService.getProfileByUserId(userId);
            if (profileOpt.isPresent()) {
                UserHealthProfile profile = profileOpt.get();
                
                // 检查是否有食品数据和自定义提示词
                if (foodData != null && !foodData.isEmpty()) {
                    // 使用食品数据和自定义提示词生成健康建议
                    deepSeekAIService.generateFoodHealthAdvice(profile, foodData, overridePrompt, emitter);
                } else if (overridePrompt != null && !overridePrompt.isEmpty()) {
                    // 如果只有自定义提示词但没有食品数据，创建一个空的食品数据Map
                    Map<String, Object> emptyFoodData = new HashMap<>();
                    deepSeekAIService.generateFoodHealthAdvice(profile, emptyFoodData, overridePrompt, emitter);
                } else {
                    // 使用默认提示词生成健康建议
                    deepSeekAIService.generateHealthAdvice(profile, emitter);
                }
            } else {
                // 如果找不到用户健康档案，返回错误信息
                emitter.send(SseEmitter.event().name("error").data("未找到用户健康档案"));
                emitter.complete();
            }
        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data("生成健康建议失败: " + e.getMessage()));
                emitter.complete();
            } catch (IOException ex) {
                emitter.completeWithError(ex);
            }
        }
        
        return emitter;
    }
}